import {defineStore} from "pinia" 
import {ref} from "vue"
import type { RouteRecordRaw} from "vue-router"
import {login,getUserInfo} from "../API/login"
import { transData,generateMenuRoutes } from "@/utils"




const useUserStroe = defineStore("user",()=>{
    const token = ref<string>("")  //token
    const userInfo= ref<IUserInfo>()  //用户基本信息
    const role = ref<IRole>() //用户角色

    const  menuRoutes = ref<RouteRecordRaw[]>([])  //菜单路由表
   

    /**
     * 登录的action方法
     * @param arg 
     */
    const loginAction= async(arg:ILoginAccount) =>{
        // const result = await login(arg)
        const {status, message, token:responseToken}= await login(arg)
        // console.log("登录结果",result)
        console.log("登录结果:",{status,message,token})
        if(status ===200){
            // 登陆成功
            token.value = responseToken as string
            return {
                success:true
            }
        }
        // 登录失败
            token.value = ""
            return {
                success:false,
                message
            }


    }
/***
 *登陆后获取用户基本信息
 */
const getUserInfoAction = async()=>{
    const result = await getUserInfo()
    // console.log("用户基本信息:",result)
    if(result.status === 200){
        userInfo.value = result.userInfo
        role.value = result.roles[0]
    }else{
        userInfo.value = undefined
        role.value  =undefined
        
    }

}

/**
 * 根据角色权限生成菜单路由表
 */
const getMenuRoutes = ()=>{
    if(!role.value?.permissions){
        return
    }
    // 获取角色权限中的菜单
    const menuPermissions = (<IPermission[]>role.value.permissions).filter(item => item.type === 1)
   console.log("menuPermissions:",menuPermissions)
   
    const _menuRoutes = generateMenuRoutes(transData(menuPermissions))
    console.log("_menuRoutes",_menuRoutes)
    menuRoutes.value = _menuRoutes
}




    return{
        token,
        userInfo,
        role,
        loginAction,
        getUserInfoAction,
        
    }
},{
    persist:{
        pick:["token"]
    }
}

)

export  default useUserStroe